package cool.mtc.minghe.web.config;

import cool.mtc.minghe.data.model.websocket.dto.WebSocketOnlineUserDTO;
import cool.mtc.minghe.service.service.websocket.WebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;

/**
 * @author 明河
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSocketConnectedListener implements ApplicationListener<SessionConnectedEvent> {
    private final WebSocketService webSocketService;

    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        log.info("SessionConnectedEvent");
        WebSocketPrincipal user = (WebSocketPrincipal) event.getUser();
        if (null == user) {
            return;
        }

        WebSocketOnlineUserDTO onlineUser = new WebSocketOnlineUserDTO();
        onlineUser.setId(user.getId());
        onlineUser.setSessionId(user.getSessionId());
        onlineUser.setName(user.getName());

        webSocketService.online(onlineUser);
    }
}
